import asyncio
import uuid
from typing import Dict, List, Any, Optional, AsyncGenerator
from datetime import datetime, timedelta
from models import (
    WorkflowState, WorkflowStatus, SessionContext, ConfirmationRequest,
    ConfirmationResponse
)
from agents import get_available_agents, get_agent, AGENT_REGISTRY
from demo_agents import detect_demo_multi_agent_requirement
from llm_service import llm_service
import logging

logger = logging.getLogger(__name__)

class WorkflowManager:
    """工作流管理器 - 负责Agent调度和工作流状态管理"""
    
    def __init__(self):
        self.active_workflows: Dict[str, WorkflowState] = {}
        self.pending_confirmations: Dict[str, ConfirmationRequest] = {}
        self.session_contexts: Dict[str, SessionContext] = {}
    
    async def process_user_input(
        self,
        session_id: str,
        user_input: str,
        context: SessionContext
    ) -> AsyncGenerator[Dict[str, Any], None]:
        """处理用户输入的主入口"""
        
        try:
            # 更新会话上下文
            self.session_contexts[session_id] = context
            context.last_activity = datetime.now()
            
            # 检查是否有待确认的工作流
            if session_id in self.active_workflows:
                workflow = self.active_workflows[session_id]
                if workflow.status == WorkflowStatus.WAITING_CONFIRMATION:
                    async for result in self._handle_confirmation_response(
                        session_id, user_input, workflow
                    ):
                        yield result
                    return
            
            # 检查是否指定了技能
            if context.skill_selected:
                selected_agent_name = context.skill_selected
                confidence = 1.0
                extracted_entities = {}
                intent_result = {
                    "selected_agent": selected_agent_name,
                    "confidence": confidence,
                    "extracted_entities": extracted_entities
                }
                logger.info(f"使用指定技能: {selected_agent_name}")
            else:
                # 首先检测是否需要多Agent协作
                logger.info(f"开始检测多Agent需求: {user_input}")
                multi_agent_result = await detect_demo_multi_agent_requirement(user_input)
                
                if multi_agent_result and len(multi_agent_result) > 1:
                    logger.info(f"检测到多Agent需求，需要的Agents: {multi_agent_result}")
                    # 创建多Agent工作流
                    async for result in self.create_multi_agent_workflow(
                        session_id, user_input, multi_agent_result, context
                    ):
                        yield result
                    return
                else:
                    logger.info(f"检测为单Agent任务，继续单Agent处理")
                    # 意图识别和Agent选择
                    available_agent_names = get_available_agents()
                    # 将Agent名称转换为包含详细信息的字典列表
                    available_agents = []
                    for agent_name in available_agent_names:
                        agent = get_agent(agent_name)
                        if agent:
                            available_agents.append({
                                "name": agent.name,
                                "description": agent.description,
                                "keywords": agent.keywords
                            })
                    
                    intent_result = await llm_service.intent_recognition(
                        user_input,
                        available_agents,
                        context.workflow_state
                    )
                    
                    selected_agent_name = intent_result.get("selected_agent", "general_chat")
                    confidence = intent_result.get("confidence", 0.0)
                    extracted_entities = intent_result.get("extracted_entities", {})
            
            logger.info(f"选择Agent: {selected_agent_name}, 置信度: {confidence}")
            
            # 获取Agent并处理
            agent = get_agent(selected_agent_name)
            if not agent:
                agent = get_agent("general_chat")
            
            # 创建工作流状态
            workflow_id = str(uuid.uuid4())
            workflow_state = WorkflowState(
                workflow_id=workflow_id,
                session_id=session_id,
                workflow_type=selected_agent_name,
                current_step="processing",
                context_data={
                    "user_input": user_input,
                    "intent_result": intent_result,
                    "extracted_entities": extracted_entities
                },
                status=WorkflowStatus.RUNNING
            )
            
            self.active_workflows[session_id] = workflow_state
            
            # 发送状态更新
            yield {
                "type": "status",
                "data": {
                    "status": "running",
                    "message": f"正在使用 {agent.description} 处理您的请求...",
                    "workflow_id": workflow_id
                }
            }
            
            # 调用Agent处理
            async for result in agent.process(user_input, context, workflow_state):
                # 检查是否需要确认
                if result.get("type") == "confirmation":
                    confirmation_id = str(uuid.uuid4())
                    # 确保data是字典类型
                    data = result.get("data", {})
                    if not isinstance(data, dict):
                        logger.error(f"确认请求数据格式错误: {type(data)}, 内容: {data}")
                        continue
                    
                    confirmation = ConfirmationRequest(
                        confirmation_id=confirmation_id,
                        message=data.get("message", "需要确认"),
                        options=data.get("options", ["确认", "取消"]),
                        workflow_id=workflow_id
                    )
                    
                    self.pending_confirmations[confirmation_id] = confirmation
                    workflow_state.status = WorkflowStatus.WAITING_CONFIRMATION
                    workflow_state.confirmation_data = {
                        "confirmation_id": confirmation_id,
                        "timeout": 300
                    }
                    
                    yield {
                        "type": "confirmation",
                        "data": confirmation.dict()
                    }
                else:
                    yield result
            
            # 更新工作流状态
            if workflow_state.status == WorkflowStatus.RUNNING:
                workflow_state.status = WorkflowStatus.COMPLETED
                workflow_state.current_step = "completed"
                
                # 发送完成状态
                yield {
                    "type": "status",
                    "data": {
                        "status": "completed",
                        "message": "请求处理完成",
                        "workflow_id": workflow_id
                    }
                }
                
                # 清理已完成的工作流
                if session_id in self.active_workflows:
                    del self.active_workflows[session_id]
            
        except Exception as e:
            import traceback
            logger.error(f"工作流处理失败: {e}")
            logger.error(f"详细错误堆栈: {traceback.format_exc()}")
            
            # 清理失败的工作流
            if session_id in self.active_workflows:
                self.active_workflows[session_id].status = WorkflowStatus.FAILED
            
            yield {
                "type": "error",
                "data": {
                    "error_code": "WORKFLOW_ERROR",
                    "error_message": f"处理失败: {str(e)}",
                    "recoverable": True
                }
            }
    
    async def _handle_confirmation_response(
        self,
        session_id: str,
        user_response: str,
        workflow: WorkflowState
    ) -> AsyncGenerator[Dict[str, Any], None]:
        """处理确认响应"""
        
        try:
            confirmation_id = workflow.confirmation_data.get("confirmation_id")
            if not confirmation_id or confirmation_id not in self.pending_confirmations:
                yield {
                    "type": "error",
                    "data": {
                        "error_code": "CONFIRMATION_NOT_FOUND",
                        "error_message": "确认请求已过期或不存在"
                    }
                }
                return
            
            confirmation_request = self.pending_confirmations[confirmation_id]
            
            # 解析用户响应
            response_result = await self._parse_confirmation_response(
                user_response,
                confirmation_request
            )
            
            if response_result.get("action") == "cancel":
                # 用户取消
                workflow.status = WorkflowStatus.CANCELLED
                del self.pending_confirmations[confirmation_id]
                if session_id in self.active_workflows:
                    del self.active_workflows[session_id]
                
                yield {
                    "type": "assistant",
                    "data": {
                        "content": "操作已取消。",
                        "is_final": True
                    }
                }
                return
            
            # 继续工作流
            workflow.status = WorkflowStatus.RUNNING
            workflow.context_data["confirmation_response"] = response_result
            workflow.current_step = "post_confirmation"
            
            # 清理确认请求
            del self.pending_confirmations[confirmation_id]
            
            # 根据确认结果继续处理
            yield {
                "type": "assistant",
                "data": {
                    "content": f"收到您的确认：{response_result.get('selected_text', user_response)}。继续处理...",
                    "is_final": True
                }
            }
            
            # 这里可以根据具体的工作流类型继续处理
            # 暂时标记为完成
            workflow.status = WorkflowStatus.COMPLETED
            if session_id in self.active_workflows:
                del self.active_workflows[session_id]
            
        except Exception as e:
            logger.error(f"确认响应处理失败: {e}")
            yield {
                "type": "error",
                "data": {
                    "error_code": "CONFIRMATION_ERROR",
                    "error_message": f"确认处理失败: {str(e)}"
                }
            }
    
    async def handle_confirmation_response(self, session_id: str, confirmation_id: str, response: str, context: SessionContext) -> AsyncGenerator[Dict[str, Any], None]:
        """公开的确认响应处理方法"""
        async for result in self._handle_confirmation_response(session_id, confirmation_id, response, context):
            yield result
    
    async def process_request(
        self,
        user_input: str,
        context: SessionContext,
        agent_name: Optional[str] = None
    ) -> AsyncGenerator[Dict[str, Any], None]:
        """处理用户请求"""
        
        session_id = context.session_id
        workflow_id = str(uuid.uuid4())
        
        try:
            logger.info(f"开始处理请求 - session_id: {session_id}, user_input: {user_input[:100]}...")
            
            # 检查是否有正在进行的工作流
            if session_id in self.active_workflows:
                existing_workflow = self.active_workflows[session_id]
                logger.info(f"发现现有工作流 - status: {existing_workflow.status}")
                
                # 如果是等待确认状态，处理确认响应
                if existing_workflow.status == WorkflowStatus.WAITING_CONFIRMATION:
                    async for result in self._handle_confirmation_response(
                        session_id, user_input, existing_workflow
                    ):
                        yield result
                    return
                
                # 如果是运行状态，继续执行
                elif existing_workflow.status == WorkflowStatus.RUNNING:
                    async for result in self._continue_workflow(
                        session_id, user_input, existing_workflow, context
                    ):
                        yield result
                    return
            
            # 检测是否需要多Agent协作
            multi_agent_requirement = await detect_demo_multi_agent_requirement(user_input)
            logger.info(f"多Agent需求检测结果: {multi_agent_requirement}")
            
            if multi_agent_requirement:
                # 创建多Agent工作流
                async for result in self.create_multi_agent_workflow(
                    session_id, user_input, context, multi_agent_requirement
                ):
                    yield result
            else:
                # 单Agent处理
                async for result in self._process_single_agent(
                    user_input, context, agent_name, workflow_id
                ):
                    yield result
                    
        except Exception as e:
            import traceback
            error_traceback = traceback.format_exc()
            logger.error(f"请求处理失败: {e}\n堆栈跟踪:\n{error_traceback}")
            yield {
                "type": "error",
                "data": {
                    "error_code": "PROCESSING_ERROR",
                    "error_message": f"处理失败: {str(e)}",
                    "recoverable": True
                }
            }
    
    async def _parse_confirmation_response(
        self,
        user_response: str,
        confirmation_request: ConfirmationRequest
    ) -> Dict[str, Any]:
        """解析用户确认响应"""
        
        # 检查取消关键词
        cancel_keywords = ["取消", "不", "否", "cancel", "no"]
        if any(keyword in user_response.lower() for keyword in cancel_keywords):
            return {"action": "cancel"}
        
        # 使用LLM解析自然语言响应
        options_str = "\n".join([f"{i+1}. {opt}" for i, opt in enumerate(confirmation_request.options)])
        
        prompt = f"""用户需要从以下选项中进行选择：

{options_str}

用户回复："{user_response}"

请分析用户的回复，返回JSON格式：
{{
    "action": "confirm",
    "selected_options": ["选项1", "选项2"],
    "selected_text": "用户实际选择的文本",
    "confidence": 0.95
}}

如果用户想取消，返回：{{"action": "cancel"}}
如果无法确定选择，返回：{{"action": "unclear", "reason": "原因"}}"""
        
        try:
            response = await llm_service.chat_completion(
                messages=[{"role": "user", "content": prompt}],
                temperature=0.1
            )
            
            import json
            # 处理不同的响应格式
            content = ""
            if hasattr(response, 'choices') and response.choices:
                # OpenAI格式响应
                content = response.choices[0].message.content
            elif isinstance(response, dict) and 'choices' in response:
                # 字典格式响应
                content = response['choices'][0]['message']['content']
            elif isinstance(response, str):
                # 直接字符串响应
                content = response
            else:
                logger.error(f"未知的响应格式: {type(response)}, 内容: {response}")
                raise ValueError("无法解析LLM响应格式")
            
            result = json.loads(content)
            return result
            
        except Exception as e:
            logger.error(f"确认响应解析失败: {e}")
            # 简单的关键词匹配作为后备
            for i, option in enumerate(confirmation_request.options):
                if option.lower() in user_response.lower():
                    return {
                        "action": "confirm",
                        "selected_options": [option],
                        "selected_text": option,
                        "confidence": 0.7
                    }
            
            return {
                "action": "unclear",
                "reason": "无法解析用户选择"
            }
    
    async def _process_single_agent(
        self,
        user_input: str,
        context: SessionContext,
        agent_name: Optional[str],
        workflow_id: str
    ) -> AsyncGenerator[Dict[str, Any], None]:
        """处理单Agent请求"""
        
        session_id = context.session_id
        
        try:
            logger.info(f"开始单Agent处理 - agent_name: {agent_name}, workflow_id: {workflow_id}")
            
            # 选择Agent
            if agent_name:
                agent = get_agent(agent_name)
                if not agent:
                    logger.error(f"Agent不存在: {agent_name}")
                    yield {
                        "type": "error",
                        "data": {
                            "error_code": "AGENT_NOT_FOUND",
                            "error_message": f"Agent '{agent_name}' 不存在"
                        }
                    }
                    return
                logger.info(f"使用指定Agent: {agent.name}")
            else:
                # 使用意图识别选择Agent
                logger.info("开始Agent选择")
                agent_selection = await self._select_agent(user_input, context)
                logger.info(f"Agent选择结果类型: {type(agent_selection)}, 内容: {agent_selection}")
                
                # 确保agent_selection是字典类型
                if not isinstance(agent_selection, dict):
                    logger.error(f"Agent选择结果不是字典类型: {type(agent_selection)}, 内容: {agent_selection}")
                    yield {
                        "type": "error",
                        "data": {
                            "error_code": "AGENT_SELECTION_ERROR",
                            "error_message": "Agent选择失败"
                        }
                    }
                    return
                
                agent = agent_selection.get("agent")
                if not agent:
                    logger.error(f"从选择结果中获取Agent失败: {agent_selection}")
                    yield {
                        "type": "error",
                        "data": {
                            "error_code": "AGENT_SELECTION_ERROR",
                            "error_message": "无法获取合适的Agent"
                        }
                    }
                    return
                
                agent_name = agent.name
                logger.info(f"选择的Agent: {agent_name}")
            
            # 创建工作流状态
            workflow_state = WorkflowState(
                workflow_id=workflow_id,
                session_id=session_id,
                status=WorkflowStatus.RUNNING,
                current_step="processing",
                context_data={"agent_name": agent_name}
            )
            
            # 注册工作流
            self.active_workflows[session_id] = workflow_state
            logger.info(f"工作流已注册: {workflow_id}")
            
            # 发送开始状态
            yield {
                "type": "status",
                "data": {
                    "status": "started",
                    "message": f"开始使用 {agent.description} 处理您的请求",
                    "agent_name": agent_name,
                    "workflow_id": workflow_id
                }
            }
            
            # 调用Agent处理
            logger.info(f"开始调用Agent处理: {agent_name}")
            async for result in agent.process(user_input, context, workflow_state):
                logger.info(f"Agent返回结果类型: {type(result)}, 内容: {result}")
                
                # 确保result是字典类型
                if not isinstance(result, dict):
                    logger.error(f"Agent返回结果不是字典类型: {type(result)}, 内容: {result}")
                    continue
                
                # 检查是否需要确认
                if result.get("type") == "confirmation":
                    confirmation_id = str(uuid.uuid4())
                    # 确保data是字典类型
                    data = result.get("data", {})
                    if not isinstance(data, dict):
                        logger.error(f"确认请求数据格式错误: {type(data)}, 内容: {data}")
                        continue
                    
                    confirmation = ConfirmationRequest(
                        confirmation_id=confirmation_id,
                        message=data.get("message", "需要确认"),
                        options=data.get("options", ["确认", "取消"]),
                        workflow_id=workflow_id
                    )
                    
                    self.pending_confirmations[confirmation_id] = confirmation
                    workflow_state.status = WorkflowStatus.WAITING_CONFIRMATION
                    workflow_state.confirmation_data = {
                        "confirmation_id": confirmation_id,
                        "timeout": 300
                    }
                    
                    yield {
                        "type": "confirmation",
                        "data": confirmation.dict()
                    }
                else:
                    yield result
            
            # 更新工作流状态
            if workflow_state.status == WorkflowStatus.RUNNING:
                workflow_state.status = WorkflowStatus.COMPLETED
                workflow_state.current_step = "completed"
                logger.info(f"工作流完成: {workflow_id}")
                
                # 发送完成状态
                yield {
                    "type": "status",
                    "data": {
                        "status": "completed",
                        "message": "请求处理完成",
                        "workflow_id": workflow_id
                    }
                }
                
                # 清理已完成的工作流
                if session_id in self.active_workflows:
                    del self.active_workflows[session_id]
            
        except Exception as e:
            import traceback
            error_traceback = traceback.format_exc()
            logger.error(f"工作流处理失败: {e}\n堆栈跟踪:\n{error_traceback}")
            
            # 清理失败的工作流
            if session_id in self.active_workflows:
                self.active_workflows[session_id].status = WorkflowStatus.FAILED
            
            yield {
                "type": "error",
                "data": {
                    "error_code": "WORKFLOW_ERROR",
                    "error_message": f"处理失败: {str(e)}",
                    "recoverable": True
                }
            }
    
    async def _select_agent(
        self,
        user_input: str,
        context: SessionContext
    ) -> Dict[str, Any]:
        """选择合适的Agent"""
        
        try:
            # 获取可用的Agent
            available_agent_names = get_available_agents()
            # 将Agent名称转换为包含详细信息的字典列表
            available_agents = []
            for agent_name in available_agent_names:
                agent = get_agent(agent_name)
                if agent:
                    available_agents.append({
                        "name": agent.name,
                        "description": agent.description,
                        "keywords": agent.keywords
                    })
            
            # 使用LLM进行意图识别
            intent_result = await llm_service.intent_recognition(
                user_input,
                available_agents,
                context.workflow_state
            )
            
            selected_agent_name = intent_result.get("selected_agent", "general_chat")
            confidence = intent_result.get("confidence", 0.0)
            
            # 获取Agent实例
            agent = get_agent(selected_agent_name)
            if not agent:
                agent = get_agent("general_chat")
                selected_agent_name = "general_chat"
            
            return {
                "agent": agent,
                "agent_name": selected_agent_name,
                "confidence": confidence,
                "intent_result": intent_result
            }
            
        except Exception as e:
            logger.error(f"Agent选择失败: {e}")
            # 返回默认Agent
            default_agent = get_agent("general_chat")
            return {
                "agent": default_agent,
                "agent_name": "general_chat",
                "confidence": 0.5,
                "intent_result": {}
            }
    
    async def _continue_workflow(
        self,
        session_id: str,
        user_input: str,
        workflow: WorkflowState,
        context: SessionContext
    ) -> AsyncGenerator[Dict[str, Any], None]:
        """继续执行现有工作流"""
        
        try:
            # 获取对应的Agent
            agent_name = workflow.context_data.get("agent_name")
            if not agent_name:
                yield {
                    "type": "error",
                    "data": {
                        "error_code": "WORKFLOW_AGENT_MISSING",
                        "error_message": "工作流中缺少Agent信息"
                    }
                }
                return
            
            agent = get_agent(agent_name)
            if not agent:
                yield {
                    "type": "error",
                    "data": {
                        "error_code": "AGENT_NOT_FOUND",
                        "error_message": f"Agent '{agent_name}' 不存在"
                    }
                }
                return
            
            # 继续处理
            async for result in agent.process(user_input, context, workflow):
                yield result
            
            # 更新工作流状态
            if workflow.status == WorkflowStatus.RUNNING:
                workflow.status = WorkflowStatus.COMPLETED
                workflow.current_step = "completed"
                
                # 清理已完成的工作流
                if session_id in self.active_workflows:
                    del self.active_workflows[session_id]
            
        except Exception as e:
            logger.error(f"工作流继续执行失败: {e}")
            yield {
                "type": "error",
                "data": {
                    "error_code": "WORKFLOW_CONTINUE_ERROR",
                    "error_message": f"工作流继续执行失败: {str(e)}"
                }
            }
    
    async def create_multi_agent_workflow(
        self,
        session_id: str,
        query: str,
        context: SessionContext,
        agents: List[str]
    ) -> AsyncGenerator[Dict[str, Any], None]:
        """创建多Agent协作工作流"""
        
        try:
            # 创建协作工作流
            workflow_id = str(uuid.uuid4())
            workflow_state = WorkflowState(
                workflow_id=workflow_id,
                session_id=session_id,
                workflow_type="multi_agent_collaboration",
                current_step="planning",
                context_data={
                    "query": query,
                    "agents": agents,
                    "execution_plan": [],
                    "results": {},
                    "current_agent_index": 0
                },
                status=WorkflowStatus.RUNNING
            )
            
            self.active_workflows[session_id] = workflow_state
            
            # 生成执行计划
            execution_plan = await self._generate_execution_plan(query, agents)
            
            # 确保execution_plan是列表类型
            if not isinstance(execution_plan, list):
                logger.error(f"生成的执行计划不是列表类型: {type(execution_plan)}, 内容: {execution_plan}")
                execution_plan = []  # 使用空列表作为默认值
            
            workflow_state.context_data["execution_plan"] = execution_plan
            
            # 安全地构建执行计划显示
            plan_display = []
            for i, step in enumerate(execution_plan):
                if isinstance(step, dict):
                    agent = step.get('agent', '未知Agent')
                    description = step.get('description', '无描述')
                    plan_display.append(f"{i+1}. {agent} - {description}")
                else:
                    plan_display.append(f"{i+1}. 无效步骤")
            
            yield {
                "type": "assistant",
                "data": {
                    "content": f"已创建多Agent协作工作流，将按以下顺序执行：\n" + "\n".join(plan_display),
                    "is_final": False
                }
            }
            
            # 执行协作流程
            async for result in self._execute_multi_agent_workflow(workflow_state, context):
                yield result
                
        except Exception as e:
            logger.error(f"多Agent协作工作流创建失败: {e}")
            yield {
                "type": "error",
                "data": {
                    "error_code": "MULTI_AGENT_WORKFLOW_ERROR",
                    "error_message": f"多Agent协作失败: {str(e)}"
                }
            }
    
    async def _generate_execution_plan(
        self,
        query: str,
        agents: List[str]
    ) -> List[Dict[str, Any]]:
        """生成多Agent执行计划"""
        
        prompt = f"""用户查询："{query}"
可用的Agent：{', '.join(agents)}

请为这个查询生成一个多Agent协作执行计划，返回JSON格式：
[
    {{
        "agent": "agent_name",
        "description": "执行描述",
        "input_dependencies": ["previous_agent_result"],
        "requires_confirmation": true/false,
        "confirmation_message": "需要确认的内容"
    }}
]

注意：
1. 按执行顺序排列
2. 考虑Agent之间的依赖关系
3. 标识需要人工确认的步骤
4. 提供清晰的执行描述"""
        
        try:
            response = await llm_service.chat_completion(
                messages=[{"role": "user", "content": prompt}],
                temperature=0.3
            )
            
            import json
            # 安全地提取content
            content = ""
            if hasattr(response, 'choices') and response.choices:
                if hasattr(response.choices[0], 'message') and hasattr(response.choices[0].message, 'content'):
                    content = response.choices[0].message.content
            elif isinstance(response, dict):
                if 'choices' in response and response['choices']:
                    choice = response['choices'][0]
                    if isinstance(choice, dict) and 'message' in choice:
                        message = choice['message']
                        if isinstance(message, dict) and 'content' in message:
                            content = message['content']
            elif isinstance(response, str):
                content = response
            
            if content:
                try:
                    plan = json.loads(content)
                    # 确保返回的是列表类型
                    if isinstance(plan, list):
                        return plan
                    elif isinstance(plan, dict) and 'plan' in plan:
                        # 如果返回的是包含plan字段的字典
                        if isinstance(plan['plan'], list):
                            return plan['plan']
                    elif isinstance(plan, dict) and 'execution_plan' in plan:
                        # 如果返回的是包含execution_plan字段的字典
                        if isinstance(plan['execution_plan'], list):
                            return plan['execution_plan']
                    
                    logger.warning(f"LLM返回的执行计划格式不正确: {type(plan)}, 内容: {plan}")
                    return []
                except json.JSONDecodeError as e:
                    logger.error(f"JSON解析失败: {e}, 内容: {content}")
                    return []
            else:
                logger.error("无法从LLM响应中提取内容")
                return []
            
        except Exception as e:
            logger.error(f"执行计划生成失败: {e}")
            # 返回默认计划
            return [
                {
                    "agent": agents[0] if agents else "global_agent",
                    "description": "处理用户查询",
                    "input_dependencies": [],
                    "requires_confirmation": False
                }
            ]
    
    async def _execute_multi_agent_workflow(
        self,
        workflow_state: WorkflowState,
        context: SessionContext
    ) -> AsyncGenerator[Dict[str, Any], None]:
        """执行多Agent协作工作流"""
        
        execution_plan = workflow_state.context_data.get("execution_plan", [])
        results = workflow_state.context_data.get("results", {})
        current_index = workflow_state.context_data.get("current_agent_index", 0)
        
        # 确保execution_plan是列表类型
        if not isinstance(execution_plan, list):
            logger.error(f"执行计划不是列表类型: {type(execution_plan)}, 内容: {execution_plan}")
            yield {
                "type": "error",
                "data": {
                    "error_code": "INVALID_EXECUTION_PLAN",
                    "error_message": "执行计划格式错误"
                }
            }
            return
        
        for i in range(current_index, len(execution_plan)):
            step = execution_plan[i]
            if not isinstance(step, dict):
                logger.error(f"执行计划步骤 {i} 不是字典类型: {type(step)}")
                continue
                
            agent_name = step.get("agent")
            if not agent_name:
                logger.error(f"执行计划步骤 {i} 缺少agent字段")
                continue
            
            # 更新当前步骤
            workflow_state.context_data["current_agent_index"] = i
            workflow_state.current_step = f"executing_{agent_name}"
            
            step_description = step.get("description", f"执行Agent {agent_name}")
            yield {
                "type": "assistant",
                "data": {
                    "content": f"正在执行步骤 {i+1}/{len(execution_plan)}: {step_description}",
                    "is_final": False
                }
            }
            
            # 检查是否需要人工确认
            if step.get("requires_confirmation", False):
                confirmation_id = str(uuid.uuid4())
                confirmation_request = ConfirmationRequest(
                    confirmation_id=confirmation_id,
                    workflow_id=workflow_state.workflow_id,
                    message=step.get("confirmation_message", f"是否继续执行 {step['description']}？"),
                    options=["继续执行", "跳过此步骤", "取消工作流"],
                    timeout=300
                )
                
                self.pending_confirmations[confirmation_id] = confirmation_request
                workflow_state.status = WorkflowStatus.WAITING_CONFIRMATION
                
                yield {
                    "type": "confirmation",
                    "data": confirmation_request.dict()
                }
                
                # 等待确认响应
                return
            
            # 执行Agent
            try:
                from agents import get_agent
                agent = get_agent(agent_name)
                if not agent:
                    yield {
                        "type": "error",
                        "data": {
                            "error_code": "AGENT_NOT_FOUND",
                            "error_message": f"未找到Agent: {agent_name}"
                        }
                    }
                    continue
                
                # 准备输入数据
                agent_input = workflow_state.context_data["query"]
                input_dependencies = step.get("input_dependencies")
                if input_dependencies and isinstance(input_dependencies, list):
                    # 合并依赖结果
                    dependency_data = []
                    for dep in input_dependencies:
                        if dep in results:
                            dependency_data.append(results[dep])
                    
                    if dependency_data:
                        agent_input += f"\n\n基于前面的结果：\n{json.dumps(dependency_data, ensure_ascii=False, indent=2)}"
                
                # 执行Agent
                agent_results = []
                async for result in agent.process(agent_input, context, workflow_state):
                    agent_results.append(result)
                    yield result
                
                # 保存结果
                results[agent_name] = agent_results
                workflow_state.context_data["results"] = results
                
            except Exception as e:
                logger.error(f"Agent {agent_name} 执行失败: {e}")
                yield {
                    "type": "error",
                    "data": {
                        "error_code": "AGENT_EXECUTION_ERROR",
                        "error_message": f"Agent {agent_name} 执行失败: {str(e)}"
                    }
                }
        
        # 工作流完成
        workflow_state.status = WorkflowStatus.COMPLETED
        workflow_state.current_step = "completed"
        
        yield {
            "type": "assistant",
            "data": {
                "content": "多Agent协作工作流已完成！",
                "is_final": True
            }
        }
    
    async def handle_skill_selection(
        self,
        session_id: str,
        skill_name: str,
        context: SessionContext
    ) -> AsyncGenerator[Dict[str, Any], None]:
        """处理技能选择"""
        
        try:
            # 更新会话上下文
            self.session_contexts[session_id] = context
            
            # 获取对应的Agent
            agent = get_agent(skill_name)
            if not agent:
                yield {
                    "type": "error",
                    "data": {
                        "error_code": "SKILL_NOT_FOUND",
                        "error_message": f"未找到技能: {skill_name}"
                    }
                }
                return
            
            # 创建工作流
            workflow_id = str(uuid.uuid4())
            workflow_state = WorkflowState(
                workflow_id=workflow_id,
                session_id=session_id,
                workflow_type=skill_name,
                current_step="skill_selected",
                context_data={"skill_name": skill_name},
                status=WorkflowStatus.RUNNING
            )
            
            self.active_workflows[session_id] = workflow_state
            
            # 返回技能介绍和使用指南
            yield {
                "type": "assistant",
                "data": {
                    "content": f"已选择技能：{agent.description}\n\n示例用法：\n" + 
                              "\n".join([f"• {example}" for example in agent.config.examples]),
                    "is_final": True
                }
            }
            
        except Exception as e:
            logger.error(f"技能选择处理失败: {e}")
            yield {
                "type": "error",
                "data": {
                    "error_code": "SKILL_SELECTION_ERROR",
                    "error_message": f"技能选择失败: {str(e)}"
                }
            }
    
    def get_session_context(self, session_id: str) -> Optional[SessionContext]:
        """获取会话上下文"""
        return self.session_contexts.get(session_id)
    
    def get_active_workflow(self, session_id: str) -> Optional[WorkflowState]:
        """获取活跃工作流"""
        return self.active_workflows.get(session_id)
    
    def cleanup_expired_workflows(self):
        """清理过期的工作流"""
        current_time = datetime.now()
        expired_sessions = []
        
        for session_id, workflow in self.active_workflows.items():
            if workflow.expires_at and current_time > workflow.expires_at:
                expired_sessions.append(session_id)
            elif current_time - workflow.updated_at > timedelta(hours=1):
                # 1小时无活动的工作流也清理
                expired_sessions.append(session_id)
        
        for session_id in expired_sessions:
            del self.active_workflows[session_id]
            if session_id in self.session_contexts:
                del self.session_contexts[session_id]
        
        # 清理过期的确认请求
        expired_confirmations = []
        for conf_id, conf in self.pending_confirmations.items():
            if current_time - conf.timestamp > timedelta(seconds=conf.timeout):
                expired_confirmations.append(conf_id)
        
        for conf_id in expired_confirmations:
            del self.pending_confirmations[conf_id]
        
        if expired_sessions or expired_confirmations:
            logger.info(f"清理了 {len(expired_sessions)} 个过期工作流和 {len(expired_confirmations)} 个过期确认")
    
    def get_workflow_stats(self) -> Dict[str, Any]:
        """获取工作流统计信息"""
        return {
            "active_workflows": len(self.active_workflows),
            "pending_confirmations": len(self.pending_confirmations),
            "active_sessions": len(self.session_contexts),
            "workflow_types": {
                wf.workflow_type: sum(1 for w in self.active_workflows.values() if w.workflow_type == wf.workflow_type)
                for wf in self.active_workflows.values()
            }
        }

# 全局工作流管理器实例
workflow_manager = WorkflowManager()

# 定期清理任务
async def periodic_cleanup():
    """定期清理过期工作流"""
    while True:
        try:
            workflow_manager.cleanup_expired_workflows()
            await asyncio.sleep(300)  # 每5分钟清理一次
        except Exception as e:
            logger.error(f"定期清理失败: {e}")
            await asyncio.sleep(60)  # 出错后1分钟后重试